package com.mall.service.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPay;
import com.mall.config.MyPayConfig;
import com.mall.dao.OrderItemMapper;
import com.mall.dao.OrderMapper;
import com.mall.dao.ProductSkuMapper;
import com.mall.entity.OrderItem;
import com.mall.entity.Orders;
import com.mall.entity.ProductSku;
import com.mall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class OrderTimeoutCheck {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Scheduled(cron = "* 0/1 * * * ?")
    public void checkAndCloseOrder() throws Exception {
        //1.查询超过30min订单状态依然为待支付状态的订单
        QueryWrapper<Orders> query = new QueryWrapper<Orders>();
        Date time=new Date(System.currentTimeMillis()-30*60*1000);
        query.eq("status", "1").lt("create_time",time);
        List<Orders> orders = orderMapper.selectList(query);
        //System.out.println(orders);
        MyPayConfig myConfig = new MyPayConfig();
        WXPay wxPay = new WXPay(myConfig);
        //取消订单
        for (int i=0;i<orders.size();i++){
            Orders order = orders.get(i);
            HashMap<String, String> map = new HashMap<>();
            map.put("out_trade_no", order.getOrderId());
            Map<String, String> resp = wxPay.orderQuery(map);
           // System.out.println(resp);
            //如果订单已经支付，将订单状态修改为待发货2
            if ("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))){
                Orders orders1 = new Orders();
                orders1.setOrderId(order.getOrderId()).setStatus("2");
                orderMapper.updateById(orders1);
            }else if("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))){
                //如果订单未支付，则取消订单
                //1.向微信支付平台发送请求，关闭当前订单的支付链接
                HashMap<String, String> closeMap = new HashMap<>();
                closeMap.put("out_trade_no", order.getOrderId());
                wxPay.closeOrder(closeMap);

                //2.修改当前订单的状态为已关闭
                orderService.closeOrder(order.getOrderId());
            }
        }
    }
}
















